package org.example.neixing;

import java.beans.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.UUID;

/**
 * 内省机制的测试代码
 */
public class Demo {

    public static void main(String[] args)
            throws InvocationTargetException, IllegalAccessException, IntrospectionException {

        // 不内省父类的信息,第二个参数stopClass代表从stopClass开始往上的父类不再内省
        BeanInfo beanInfo = Introspector.getBeanInfo(Person.class, Object.class);

        // new 一个 Person  对象
        Person person = new Person(UUID.randomUUID().toString(), "Mr_nobody", 18);

        /**
         * 属性遍历
         */
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            Class<?> propertyType = propertyDescriptor.getPropertyType();
            String propertyName = propertyDescriptor.getName();
            Method readMethod = propertyDescriptor.getReadMethod();
            Method writeMethod = propertyDescriptor.getWriteMethod();

            System.out.println("属性名：" + propertyName);
            System.out.println("属性类型：" + propertyType);
            System.out.println("写方法名：" + writeMethod.getName());
            System.out.println("读方法名：" + readMethod.getName());

            if ("age".equals(propertyName)) {
                writeMethod.invoke(person, 20);
            }
            System.out.println("属性值：" + readMethod.invoke(person));
            System.out.println("------------------------------------------");
        }

        /**
         * 方法遍历
         */
        MethodDescriptor[] methodDescriptors = beanInfo.getMethodDescriptors();
        for (MethodDescriptor methodDescriptor : methodDescriptors) {

            Method method = methodDescriptor.getMethod();
            System.out.println(method);
            System.out.println("方法名：" + method.getName());

            Type[] genericParameterTypes = method.getGenericParameterTypes();
            if (genericParameterTypes != null) {
                for (Type genericParameterType : genericParameterTypes) {
                    System.out.println("方法参数类型：" + genericParameterType.getTypeName());
                }
            }

            Class<?> returnType = method.getReturnType();
            System.out.println("方法返回类型：" + returnType.getTypeName());
            System.out.println("---------------------------");
        }
    }
}